import express from 'express';
// 引入评论相关控制器
import * as comments from '../../controllers/comments.js'
const router = express.Router();

// 6. 最新评论  (最新的6条评论，跨所有文章)    
router.get("/latest_comment", async (req, res, next) => {
  try {
    console.log('开始处理 /latest_comment 请求...');
    // 使用SQL的SUBSTRING函数截取评论内容到50个字符，超过则显示...
    let sql = `select author, date, 
               CASE 
                 WHEN CHAR_LENGTH(content) > 50 THEN CONCAT(SUBSTRING(content, 1, 50), '...') 
                 ELSE content 
               END as intro 
               from comments where state = ? order by date desc, time desc limit 6`;
    let { executeSql } = await import('../../util/db.js');
    let data = await executeSql(sql, ['已通过']);
    res.send({
      code: 200,
      msg: "查询成功",
      data: data.map(item => ({
        author: item.author,
        date: item.date,
        intro: item.intro
      }))
    });
  } catch (error) {
    next(error);
  }
});

// 9. 发表评论接口 
router.post("/post_comment", async (req, res, next) => {
  try {
    console.log('开始处理 /post_comment 请求...');
    // console.log(req.body);
    const { author, content, articleId } = req.body;
    if (!author || !content || !articleId) {
      return res.status(400).send({
        code: 400,
        msg: "参数不完整"
      });
    }
    await comments.insertComment(author, content, articleId);
    res.send({
      code: 200,
      msg: "发表成功"
    });
  } catch (error) {
    res.status(500).send({
      code: 500,
      msg: "发表失败"
    });
  }
});

// 10. 评论列表接口
router.get("/get_comment", async (req, res, next) => {
  try {
    console.log('开始处理 /get_comment 请求...');
    const { articleId } = req.query;
    
    if (!articleId) {
      return res.status(400).send({
        code: 400,
        msg: "文章ID不能为空"
      });
    }
    
    let data = await comments.selectCommentsByArticleId(articleId);
    
    res.send({
      code: 200,
      msg: "查询成功",
      data: data.map(item => ({
        author: item.author,
        date: item.date,
        content: item.content
      }))
    });
  } catch (error) {
    console.error('get_comment接口错误:', error.message);
    res.status(500).send({
      code: 500,
      msg: "查询失败: " + error.message
    });
  }
});

export default router;
